package com.zhudoo.zhilian.dao.impl;

import com.zhudoo.zhilian.dao.entity.Appointment;
import com.zhudoo.zhilian.dao.repository.AppointmentRepository;
import com.zhudoo.zhilian.service.AppointmentService;
import com.zhudoo.zhilian.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author zhudao
 */
@Component
public class AppointmentDao {

    @Autowired
    private AppointmentRepository appointmentRepository;

    public void saveAppointment(Appointment appointment) {
        appointmentRepository.save(appointment);
    }

    public List<Appointment> getAppointmentList(Integer userId, Integer userType, Integer status, Integer page, Integer limit) {
        Pageable pageable = PageRequest.of(page - 1, limit, Sort.by("createTime").descending());
        Set<Integer> set = new HashSet<>();
        if (status == 0) {
            set.add(AppointmentService.APPOINTMENT_STATUS_1);
            set.add(AppointmentService.APPOINTMENT_STATUS_2);
        } else {
            set.add(AppointmentService.APPOINTMENT_STATUS_3);
            set.add(AppointmentService.APPOINTMENT_STATUS_4);
            set.add(AppointmentService.APPOINTMENT_STATUS_5);
        }
        if (userType == UserService.TYPE_1) {
            return appointmentRepository.findAllByToUserIdAndStatusIn(userId, set, pageable);
        } else {
            return appointmentRepository.findAllByUserIdAndStatusIn(userId, set, pageable);
        }
    }

    public Appointment getAppointmentById(Integer id) {
        return appointmentRepository.getOne(id);
    }

    public Appointment getAppointmentByUserIdAndAcceptUserIdAndStatusIn(Integer userId, Integer acceptUserId, Set<Integer> status) {
        return appointmentRepository.findByUserIdAndToUserIdAndStatusIn(userId, acceptUserId, status);
    }

    public Appointment getAppointmentBy(Integer userId, Integer acceptUserId, Set<Integer> status) {
        return appointmentRepository.findByUserIdAndToUserIdAndStatusIn(userId, acceptUserId, status);
    }

    public Appointment getAppointmentByOnlyStr(String onlyStr) {
        return appointmentRepository.findByOnlyStr(onlyStr);
    }
}
